package org.database.filter.service.impl;

import org.database.filter.model.NhaDauTuDoanhNghiep;
import org.database.filter.repository.NhaDauTuDoanhNghiepRepository;
import org.database.filter.service.NhaDauTuDoanhNghiepService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class NhaDauTuDoanhNghiepServiceImpl implements
		NhaDauTuDoanhNghiepService {
	private static final int MAX_NAME_LENGTH = 199;
	private static final String GP_CHARACTER = "gp:";
	@Autowired
	private NhaDauTuDoanhNghiepRepository nhaDauTuDoanhNghiepRepository;

	public int saveOrUpdate(NhaDauTuDoanhNghiep nhaDauTuDoanhNghiep) {
		if(nhaDauTuDoanhNghiep.getTENDN() != null) {
			nhaDauTuDoanhNghiep.setTENDN(nhaDauTuDoanhNghiep.getTENDN().replace(GP_CHARACTER, ""));
		}
		if (nhaDauTuDoanhNghiep.getTENDN() != null
				&& nhaDauTuDoanhNghiep.getTENDN().length() > MAX_NAME_LENGTH) {
			nhaDauTuDoanhNghiep.setTENDN(nhaDauTuDoanhNghiep.getTENDN()
					.substring(0, MAX_NAME_LENGTH));
		}
		if (nhaDauTuDoanhNghiep.getDIACHI() != null
				&& nhaDauTuDoanhNghiep.getDIACHI().length() > MAX_NAME_LENGTH) {
			nhaDauTuDoanhNghiep.setDIACHI(nhaDauTuDoanhNghiep.getDIACHI()
					.substring(0, MAX_NAME_LENGTH));
		}
		try {
			nhaDauTuDoanhNghiep = nhaDauTuDoanhNghiepRepository
					.saveAndFlush(nhaDauTuDoanhNghiep);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return nhaDauTuDoanhNghiep.getID_DN();
	}
}
